package controllers

import (
	"api.rcenet.com/utils"
	"smart_home/admin/commons"
	"smart_home/admin/models"
	"time"
	"tools"
)

type LoginController struct {
	BaseController
}

// @title 登陆
// @router / [post]
func (c *AdminController) Login() {
	var userName, password string
	c.Ctx.Input.Bind(&userName, "user_name")
	c.Ctx.Input.Bind(&password, "password")

	// 查找用户
	data, err := models.GetAdminByName(userName)
	if err != nil {
		c.ErrorResponse(commons.ErrorDBError)
		return
	}
	if data == nil {
		c.ErrorResponse(commons.ErrorUserNotExits)
		return
	}

	// 比对密码
	if data.Password != utils.MD5Encode(password) {
		c.ErrorResponse(commons.ErrorPassword)
		return
	}

	token := tools.GUUID()
	timeout := 3600 * 24
	if err := commons.Cache.Put(token, data.Id, time.Duration(timeout)); err != nil {
		c.ErrorResponse(commons.ErrorLoginFail)
		return
	}

	c.SuccessResponse(map[string]interface{}{
		"user_id": data.Id,
		"token":   token,
		"timeout": timeout,
	})
}
